#include "System.h"

#include <QDebug>

#include "DeviceManager.h"

System* System::instance()
{
    static System instance;
    return &instance;
}

System::System(QObject* parent) : QObject(parent)
{
    // 初始化子系统
    m_configManager = SystemConfigManager::instance();
    m_scheduler = new SystemScheduler(this);

    // 建立连接
    initConnections();
}

System::~System() {}

void System::initConnections()
{
    // 转发配置管理器的信号
    connect(m_configManager, &SystemConfigManager::configChanged, this, &System::configChanged);

    // 转发调度器的信号
    connect(m_scheduler, &SystemScheduler::infoChanged, this, &System::infoChanged);
    connect(m_scheduler, &SystemScheduler::isRunningChanged, this, &System::isRunningChanged);
    connect(m_scheduler, &SystemScheduler::currentTaskChanged, this, &System::currentTaskChanged);
    connect(m_scheduler, &SystemScheduler::taskFailed, this, &System::taskFailed);
    connect(m_scheduler, &SystemScheduler::taskCompleted, this, &System::taskCompleted);

    // 监听配置变化，通知调度器更新
    connect(m_configManager, &SystemConfigManager::configChanged, m_scheduler,
            &SystemScheduler::updateNextTimes);

    // 连接设备管理器的测量超标信号
    DeviceManager* deviceManager = DeviceManager::instance();
    connect(deviceManager, &DeviceManager::measurementOutOfRange, this,
            &System::onMeasurementOutOfRange);
}

void System::start()
{
    qDebug() << "System: 启动系统";
    m_scheduler->start();
}

void System::stop()
{
    qDebug() << "System: 停止系统";
    m_scheduler->stop();
}

bool System::isRunning() const { return m_scheduler->isRunning(); }

SystemConfig System::getConfig() const { return m_configManager->getConfig(); }

bool System::setConfig(const SystemConfig& config) { return m_configManager->setConfig(config); }

bool System::checkConfigTimeConflict(const SystemConfig& config)
{
    return m_configManager->checkTimeConflict(config);
}

bool System::isScheduled(int hour) const { return m_configManager->isScheduled(hour); }

SystemInfo System::getInfo() const { return m_scheduler->getInfo(); }

QString System::getTaskName(qint16 operateCode) const
{
    return m_scheduler->getTaskName(operateCode);
}

void System::execTask(qint16 operateCode) { m_scheduler->executeTask(operateCode); }

void System::setTaskCondition(const QString& key, bool value)
{
    m_scheduler->setTaskCondition(key, value);
}

void System::onMeasurementOutOfRange(const QString& deviceName, float value, float lowerLimit,
                                     float upperLimit)
{
    qDebug() << "设备" << deviceName << "测量值超出范围:" << value << "范围:[" << lowerLimit << ","
             << upperLimit << "]";

    // 设置不排水条件，当测值超标时不执行排水步骤
    setTaskCondition("need_drain", false);

    qDebug() << "由于测值超标，已设置不排水条件";
}